import time

import cv2
import mediapipe as mp



class HandDetector():
    def __init__(self, mode=False,
                maxHands=2,
                model_complexity=1,
                detectionCon=0.5,
                 trackCon=0.5):

        self.mode = mode
        self.maxHands = maxHands
        self.model_complexity = model_complexity
        self.detectionCon = detectionCon
        self.trackCon = trackCon
        self.mpHands = mp.solutions.hands
        self.hands = self.mpHands.Hands(self.mode,self.maxHands,self.model_complexity,
                                        self.detectionCon,self.trackCon)
        self.mpDraw = mp.solutions.drawing_utils

    def findHands(self, frame, draw=True):

        imgRGB = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        self.results = self.hands.process(imgRGB)
        # print(results.multi_hand_landmarks)

        if self.results.multi_hand_landmarks:
            for handLms in self.results.multi_hand_landmarks:
                if draw:
                    self.mpDraw.draw_landmarks(frame, handLms,
                                               self.mpHands.HAND_CONNECTIONS)
        return frame
                # for id, lm in enumerate(handlms.landmark):
                #     h, w, c = frame.shape
                #     cx, xy = int(lm.x * w), int(lm.y * h)
                #     if id == 4:
                #         cv2.circle(frame, (cx, xy), 25, (255, 0, 255), cv2.FILLED)
                    # cv2.circle(frame,(cx,xy),5,(255,0,255),cv2.FILLED)

def main():
    cap = cv2.VideoCapture(0)
    detector = HandDetector()
    Ptime = 0
    while True:
        ret, frame = cap.read()
        frame = detector.findHands(frame)
        Ctime = time.time()
        fps = 1 / (Ctime - Ptime)
        Ptime = Ctime
        cv2.putText(frame, f'fps:{int(fps)}', (10, 70), cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 255), 2)
        cv2.imshow('frame', frame)
        cv2.waitKey(45)


if __name__ == '__main__':
    main()